using System;
using System.Runtime.InteropServices;
using Avalonia.Input;

namespace IntegratedMeasuring.Utils;

/// <summary>
/// 全局热键管理器
/// </summary>
public class HotKeyManager : IDisposable
{
    // Windows API常量
    public const int WM_HOTKEY = 0x0312;
    
    // Windows API函数声明
    [DllImport("user32.dll")]
    private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);
    
    [DllImport("user32.dll")]
    private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
    
    [DllImport("kernel32.dll")]
    private static extern uint GlobalAddAtom(string lpString);
    
    [DllImport("kernel32.dll")]
    private static extern uint GlobalDeleteAtom(uint nAtom);
    
    [DllImport("kernel32.dll")]
    private static extern uint GlobalFindAtom(string lpString);
    
    [DllImport("user32.dll")]
    private static extern short GetAsyncKeyState(int vKey);
    
    // 热键ID
    private int _hotKeyId;
    
    // 窗口句柄
    private IntPtr _windowHandle;
    
    // 热键触发事件
    public event EventHandler? HotKeyPressed;
    
    public HotKeyManager(IntPtr windowHandle)
    {
        _windowHandle = windowHandle;
        _hotKeyId = (int)GlobalAddAtom("IntegratedMeasuring_HotKey");
    }
    
    /// <summary>
    /// 注册热键
    /// </summary>
    /// <param name="modifier">修饰键</param>
    /// <param name="key">主键</param>
    /// <returns>是否注册成功</returns>
    public bool RegisterHotKey(KeyModifiers modifier, Key key)
    {
        uint fsModifiers = ConvertModifierKeys(modifier);
        uint vk = (uint)key;
        
        return RegisterHotKey(_windowHandle, _hotKeyId, fsModifiers, vk);
    }
    
    /// <summary>
    /// 注销热键
    /// </summary>
    public void UnregisterHotKey()
    {
        UnregisterHotKey(_windowHandle, _hotKeyId);
    }
    
    /// <summary>
    /// 处理窗口消息
    /// </summary>
    /// <param name="msg">消息ID</param>
    /// <param name="wParam">参数1</param>
    /// <param name="lParam">参数2</param>
    /// <returns>是否处理了消息</returns>
    public bool ProcessMessage(int msg, IntPtr wParam, IntPtr lParam)
    {
        if (msg == WM_HOTKEY && wParam.ToInt32() == _hotKeyId)
        {
            HotKeyPressed?.Invoke(this, EventArgs.Empty);
            return true;
        }
        return false;
    }
    
    /// <summary>
    /// 检查热键是否被按下（备用方法）
    /// </summary>
    /// <param name="modifier">修饰键</param>
    /// <param name="key">主键</param>
    /// <returns>是否按下</returns>
    public bool IsHotKeyPressed(KeyModifiers modifier, Key key)
    {
        // 检查修饰键
        bool ctrlPressed = (modifier & KeyModifiers.Control) != 0 && (GetAsyncKeyState(0x11) & 0x8000) != 0;
        bool altPressed = (modifier & KeyModifiers.Alt) != 0 && (GetAsyncKeyState(0x12) & 0x8000) != 0;
        bool shiftPressed = (modifier & KeyModifiers.Shift) != 0 && (GetAsyncKeyState(0x10) & 0x8000) != 0;
        
        // 检查主键
        bool keyPressed = (GetAsyncKeyState((int)key) & 0x8000) != 0;
        
        return ctrlPressed && keyPressed; // 简化处理，只检查Ctrl+Key
    }
    
    /// <summary>
    /// 转换修饰键
    /// </summary>
    private uint ConvertModifierKeys(KeyModifiers modifier)
    {
        uint result = 0;
        
        if ((modifier & KeyModifiers.Alt) != 0)
            result |= 0x0001; // MOD_ALT
        if ((modifier & KeyModifiers.Control) != 0)
            result |= 0x0002; // MOD_CONTROL
        if ((modifier & KeyModifiers.Shift) != 0)
            result |= 0x0004; // MOD_SHIFT
        if ((modifier & KeyModifiers.Meta) != 0)
            result |= 0x0008; // MOD_WIN
            
        return result;
    }
    
    public void Dispose()
    {
        UnregisterHotKey();
        if (_hotKeyId != 0)
        {
            GlobalDeleteAtom((uint)_hotKeyId);
        }
    }
} 